# -*- coding: utf-8 -*-
"""
@Time : 2023/7/28 17:11
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : borrow_book.py
"""

import sys
import datetime
from flask_restful import Resource, reqparse

from service.mysql_connect import MySQLConnected
from service.config_import import load_yaml

sys.path.append('..')

parser = reqparse.RequestParser()
parser.add_argument('book_id', type=int, help="参数book_id不能为空", required=True)
parser.add_argument('borrower_id', type=int, help="参数borrower_id不能为空", required=True)


class BorrowBook(Resource):
    def post(self):
        args = parser.parse_args()
        book_id = args.get('book_id')
        borrower_id = args.get('borrower_id')
        yaml_config_path = "config_info.yaml"
        params = load_yaml(yaml_config_path)
        dbinfo = params['databases']['library_db_info']
        # print(dbinfo)
        db = params['databases']['library_db_name']
        connected = MySQLConnected(dbinfo)

        sql_for_book_status = "select valid,status from " + db + ".books where id = %s"
        connected.cur.execute(sql_for_book_status, str(book_id))
        book_status = connected.cur.fetchall()
        print(book_status)
        if not book_status:
            return {'content': '不存在对应书籍，请确认', 'result': 'failure'}
        for b_s in book_status:
            book_valid, book_status = b_s
        print("书籍valid", book_valid)
        print("书籍借用状态status", book_status)
        if book_valid == 0:
            return {'content': '书籍不可用，请借阅其他图书', "result": 'failure'}
        if book_status == 0:
            return {'content': '书籍已被他人借阅，请联系对应借阅人', 'result': 'failure'}

        sql_for_borrower_status = "select valid from " + db + ".borrowers where id = %s"
        connected.cur.execute(sql_for_borrower_status, str(borrower_id))
        borrower_status = connected.cur.fetchall()
        if not borrower_status:
            return {'content': '不存在对应人员，请确认', 'result': 'failure'}
        for b_s in borrower_status:
            borrower_valid, = b_s
        print(borrower_valid, type(borrower_valid))
        if borrower_valid == 0:
            return {'content': '人员已离职，不能进行书籍借用', 'result': 'failure'}

        sql_update_book_status = "update " + db + ".books set status = 0 where id = %s"
        connected.cur.execute(sql_update_book_status, book_id)

        # CREATE TABLE `books_borrowers_relation`(
        #     `id` int NOT NULL AUTO_INCREMENT,
        #     `book_id` int NOT NULL COMMENT '书籍id',
        #     `borrower_id` int NOT NULL COMMENT '人员id',
        #     `valid` int NOT NULL DEFAULT '1' COMMENT '借用关系状态,1-有效,0-无效',
        #     `borrow_time` varchar(50) DEFAULT NULL COMMENT '借用时间',
        #     `return_time` varchar(50) DEFAULT NULL COMMENT '归还时间',
        #     constraint fk_book_id foreign key(book_id) references books(id),
        #     constraint fk_borrower_id foreign key(borrower_id) references borrowers(id),
        #     PRIMARY KEY(`id`)
        # ) ENGINE = InnoDB DEFAULT CHARSET = utf8;
        now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        sql = "insert into " + db + ".books_borrowers_relation (book_id,borrower_id,valid,borrow_time) " + \
              "values (%s,%s,1," + now + ")"
        # sql = "update " + db + ".books set valid = not valid where id = %s"
        connected.cur.execute(sql, (str(book_id), str(borrower_id)))

        connected.con.commit()
        connected.cur.close()
        connected.con.close()

        return {'content': "借书成功", 'result': 'success'}
